//
//  ACArticleFontSelectView.m
//  acfun_video
//
//  Created by user on 11/23/15.
//  Copyright © 2015 wang. All rights reserved.
//
#define UICOLOR_MAKE_RGBINT(rgbInt) UICOLOR_MAKE_RGBINT_A(rgbInt,1)
#define UICOLOR_MAKE_RGBINT_A(rgbInt,a) [UIColor colorWithRed:((float)((rgbInt & 0xFF0000) >> 16))/255.0 green:((float)((rgbInt & 0xFF00) >> 8))/255.0 blue:((float)(rgbInt & 0xFF))/255.0 alpha:a]


#define SCREEN_WIDTH                    ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT                   ([UIScreen mainScreen].bounds.size.height)



#import "ACArticleSettingAlertView.h"
//#import "ACSettingsMethod.h"
#import "UIView+TKExtension.h"
#import "UIView+Utilities.h"

#define ACArticleCicleButtonBaseTag 1000

///圆点的直径
static const CGFloat ACArticleCirlceInnerDiameter           =   8.;
///圆点的直径,除以2,也就是距离顶部的高的
static const CGFloat ACArticleCirlceOutterDiameter          =   60;
///横向选择视图的高度
static const CGFloat ACArticleHorizonSelectionViewHeight    =   ACArticleCirlceOutterDiameter + 17 + 12;
///左侧title的leftmargin
static const CGFloat ACArticleFirstTitleLeftMargin               =   15;
///右侧title的rightMargin
static const CGFloat ACArticleLastTitleRightMargin               =   18;
///选中的小indicator得width
static const CGFloat ACArticleSelectedIndicatorWidth             = 20;

UIColor *ACArticleLineStrokeColor() {
    return [UIColor blackColor];
}

UIColor *ACArticleNormalColor() {
    return [UIColor blueColor];
}

UIColor *ACArticleSelectedColor() {
    return [UIColor redColor];
}

NSString *ACArticleFontTitle(ACArticleFontType type) {
    switch (type) {
        case ACArticleSmallFont:
            return @"非常小";
            break;
        case ACArticleNormalFont:
            return @"标准";
            break;
        case ACArticleLittleLargeFont:
            return @"有点大";
            break;
        case ACArticleLargeFont:
            return @"特别大";
            break;
        default:
            return @"";
            break;
    }
}

CGFloat ACArticleFontSize(ACArticleFontType type) {
    switch (type) {
        case ACArticleSmallFont:
            return 12;
            break;
        case ACArticleNormalFont:
            return 14;
            break;
        case ACArticleLittleLargeFont:
            return 16;
            break;
        case ACArticleLargeFont:
            return 18;
            break;
        default:
            return 14;
            break;
    }
}

CGFloat  ACArticleFontScale(ACArticleFontType type) {
    switch (type) {
        case ACArticleSmallFont:
            return 0.8;
            break;
        case ACArticleNormalFont:
            return 1.0;
            break;
        case ACArticleLittleLargeFont:
            return 1.2;
            break;
        case ACArticleLargeFont:
            return 1.4;
            break;
        default:
            return 1.0;
            break;
    }
}

CGFloat  ACArticleFontScaleInSetting() {
    return ACArticleFontScale(ACArticleFontTypeInSetting());
}

NSArray *ACArticleFontTitles() {
    return @[ACArticleFontTitle(ACArticleSmallFont),ACArticleFontTitle(ACArticleNormalFont),ACArticleFontTitle(ACArticleLittleLargeFont),ACArticleFontTitle(ACArticleLargeFont)];
}

CGFloat  ACArticleFontTargetFontTypeFromCurrentFontType(ACArticleFontType targetFontType,ACArticleFontType currentFontType) {
    CGFloat currentFont = ACArticleFontScale(currentFontType);
    CGFloat targetFont = ACArticleFontScale(targetFontType);
    return targetFont / currentFont;
}

NSInteger ACArticleTypesCount() {
    return ACArticleFontTitles().count;
}

@implementation ACArticleSettingAlertView {
    UIButton            *_btnDismiss;
    dispatch_block_t    dimDismiss;
    dispatch_block_t    confirmAction;
    void(^fontChangedAction)(CGFloat);
}

+ (instancetype)articleSettingView {
    return [[self alloc] init];
}

- (instancetype)init {
    if (self = [super initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 0)]) {
        self.backgroundColor = [UIColor whiteColor];
        CGFloat leftMargin = 10;
        CGFloat nextTop = 15;//记录控件子视图所占总高度(在子视图初始化之后+子视图.height+y)用于计算self.height
        CGFloat verticalMargin = 10;
        UIFont *titleFont = [UIFont boldSystemFontOfSize:16];
//        UIFont *subtitleFont = [UIFont systemFontOfSize:15];
        ///文字大小
        UILabel *lblFontSetting = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, nextTop, SCREEN_WIDTH - leftMargin * 2, 0)];
        lblFontSetting.text = @"调整正文字号";
        lblFontSetting.font = titleFont;
        lblFontSetting.textColor = UICOLOR_MAKE_RGBINT(0x333333);
        [lblFontSetting sizeToFit];
        nextTop = lblFontSetting.bottom + verticalMargin;
        
        CGFloat pointToPixel = 1 / [UIScreen mainScreen].scale;
        UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, nextTop, SCREEN_WIDTH, pointToPixel)];
        separator.backgroundColor = UICOLOR_MAKE_RGBINT(0xcccccc);
        nextTop += 1;
        
        __weak ACArticleSettingAlertView *weakSelf = self;
        ACArticleHorizonSelectionView *selections = [[ACArticleHorizonSelectionView alloc] initWithFrame:CGRectMake(0, nextTop, SCREEN_WIDTH, 0) selections:ACArticleFontTitles() defaultSelectIndex:ACArticleFontTypeInSetting()];
        [selections didChangeFontAction:^(CGFloat scale){//设置字体改变的block
            [weakSelf handleFontChangedAction:scale];
        }];
        nextTop = selections.bottom + verticalMargin;
        
        
//        ///无图模式
//        UILabel *lblImageModeSetting = [[UILabel alloc] initWithFrame:CGRectMake(lblFontSetting.left, nextTop, lblFontSetting.width, 0)];
//        lblImageModeSetting.text = @"无图模式";
//        lblImageModeSetting.font = titleFont;
//        [lblImageModeSetting sizeToFit];
//        nextTop = lblImageModeSetting.bottom + verticalMargin;
//        
//        CGFloat stOnoffWidth = 70;
//        ///是否允许在移动网络下加载图片
//        UILabel *lblSubImageMode = [[UILabel alloc] initWithFrame:CGRectMake(lblFontSetting.left, nextTop, SCREEN_WIDTH - leftMargin * 2 - stOnoffWidth, 0)];
//        lblSubImageMode.text = @"允许在移动网络下加载文章图片";
//        lblSubImageMode.numberOfLines = 0;
//        lblSubImageMode.font = subtitleFont;
//        lblSubImageMode.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
//        [lblSubImageMode sizeToFit];
//        
//        UISwitch *stOnOff = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - stOnoffWidth, nextTop, 50, 30)];
//        stOnOff.center = CGPointMake(stOnOff.center.x, lblSubImageMode.center.y);
//        stOnOff.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
//        
//        nextTop = lblSubImageMode.bottom + verticalMargin * 2;
//        
//        ///添加
//        CGFloat pointToPixel = 1 / [UIScreen mainScreen].scale;
//        UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, nextTop, SCREEN_WIDTH, pointToPixel)];
//        separator.backgroundColor = [UIColor blackColor];
//        nextTop += 1;
//        
//        UIButton *btnConfirm = [UIButton buttonWithType:UIButtonTypeCustom];
//        btnConfirm.frame = CGRectMake(0, nextTop, SCREEN_WIDTH, 44);
//        [btnConfirm setTitle:@"确  定" forState:UIControlStateNormal];
//        [btnConfirm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        [btnConfirm addTarget:self action:@selector(didClickConfirmAction:) forControlEvents:UIControlEventTouchUpInside];
//        
//        nextTop = btnConfirm.bottom;
        self.height = nextTop;
        [self addSubview:lblFontSetting];
        [self addSubview:separator];
        [self addSubview:selections];
//        [self addSubview:lblImageModeSetting];
//        [self addSubview:lblSubImageMode];
//        [self addSubview:stOnOff];
//        [self addSubview:btnConfirm];
    }
    return self;
}

/*!
 *  显示alertview
 */
- (void)show {
    UIWindow *keyWindow = [[UIApplication sharedApplication].delegate window];
    [self btnDismiss].alpha = 0.0;
    self.top = -self.height;
    [keyWindow addSubview:[self btnDismiss]];
    [keyWindow addSubview:self];
    [UIView animateWithDuration:.3 animations:^{
        [self btnDismiss].alpha = 1.;
        self.top = 64;
    }];
}
/*!
 *  隐藏alertView
 */
- (void)dismiss {
    [UIView animateWithDuration:.3 animations:^{
        [self btnDismiss].alpha = 0.0;
        self.top = -self.height;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
/*!
 *  点击暗色背景消失的回调
 */
- (void)didDismissOnDimBackground:(dispatch_block_t)action {
    dimDismiss = action;
}

- (void)didConfirmAction:(dispatch_block_t)action {
    confirmAction = action;
}

- (void)didChangeFontAction:(void(^)(CGFloat))action {
    fontChangedAction = action;
}

- (UIButton *)btnDismiss {
    if (!_btnDismiss) {
        UIWindow *keyWindow = [[UIApplication sharedApplication].delegate window];
        _btnDismiss = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnDismiss.frame = keyWindow.bounds;
        _btnDismiss.backgroundColor = [UICOLOR_MAKE_RGBINT(0x515151) colorWithAlphaComponent:.5];
        [_btnDismiss addTarget:self action:@selector(dismissWithAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnDismiss;
}

#pragma mark - Actions
- (void)dismissWithAction:(UIButton *)btn {
    if (dimDismiss) {
        dimDismiss();
    }
    [self dismiss];
}

- (void)didClickConfirmAction:(UIButton *)btn {
    ///1.dismiss本视图
    ///2.记录当前的setting
    ///3.回调看是否刷新界面
    if (confirmAction) {
        confirmAction();
    }
    [self dismiss];
}

- (void)handleFontChangedAction:(CGFloat)scale {
    if (fontChangedAction) {
        fontChangedAction(scale);
    }
}

@end

@implementation ACArticleHorizonSelectionView {
    ///水平线
    CAShapeLayer        *slCicles;
    ///渐变layer
    CAGradientLayer     *glGradientCircles;
    ///渐变layer的masklayer 
    UIView              *maskView;
    ///选中的circle
    UIImageView         *vSelected;
    ///选中的index
    NSInteger           selectedIndex;
    ///第一个title的x坐标
    CGFloat             firstTitleCenterX;
    ///最后一个title的x坐标
    CGFloat             lastTitleCenterX;
    ///每一段的宽度
    CGFloat             sliceWidth;
    ///全部数量
    NSInteger           totalSelectionsCount;
    ///圆圈数组
    NSArray             *arrCircles;
    void(^fontChangedAction)(CGFloat);
}

- (instancetype)initWithFrame:(CGRect)frame selections:(NSArray *)selections defaultSelectIndex:(NSInteger)defaultSelectIndex {
    if (self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, ACArticleHorizonSelectionViewHeight)]) {
        self.clipsToBounds = YES;
        
        ///计算基本数值
        selectedIndex = defaultSelectIndex;
        totalSelectionsCount = selections.count;
        
        CGSize titleSize = [ACArticleFontTitle(ACArticleSmallFont) sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:ACArticleFontSize(ACArticleSmallFont)]}];//算出最左侧文字宽度
        firstTitleCenterX = ACArticleFirstTitleLeftMargin + titleSize.width / 2;//第一个点的中点是左侧间距+最左侧文字宽度*0.5
        titleSize = [ACArticleFontTitle(ACArticleLargeFont) sizeWithAttributes:@{NSAttachmentAttributeName: [UIFont systemFontOfSize:ACArticleFontSize(ACArticleLargeFont)]}];//算出最右侧文字宽度
        lastTitleCenterX = self.width - ACArticleLastTitleRightMargin - titleSize.width / 2;//最后一个点的中点为 宽度-最后文字宽度*0.5-本身距离右边的间距
        
        sliceWidth = (lastTitleCenterX - firstTitleCenterX) / (totalSelectionsCount - 1);//最后中心点-第一个中心点／(title个数-1）
        
        ///生成gradientlayer的mask
        slCicles = [self generateShapeLayer];//与自己同大小透明的shapeLayer
        
        UIBezierPath *bpHorizonLine = [UIBezierPath bezierPathWithRect:CGRectMake(firstTitleCenterX, ACArticleCirlceOutterDiameter / 2 - 1, lastTitleCenterX - firstTitleCenterX, 2)];
        maskView = [[UIView alloc] initWithFrame:self.bounds];
        maskView.clipsToBounds = YES;
        maskView.userInteractionEnabled = NO;
        glGradientCircles = [self gradientLineLayer];
        ///添加圆圈
        NSMutableArray *marrCicles = [NSMutableArray arrayWithCapacity:totalSelectionsCount];
        CGFloat step = -1;
        for (NSInteger index = 0; index < selections.count; index++) {
            CGPoint circleCenter = [self circleCenterAtIndex:index];
            [bpHorizonLine moveToPoint:[self circleCenterAtIndex:index]];
            [bpHorizonLine addArcWithCenter:circleCenter radius:ACArticleCirlceInnerDiameter / 2 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
            if (index != totalSelectionsCount - 1) {
                [bpHorizonLine addLineToPoint:[self circleCenterAtIndex:index + 1]];
            }
            UIButton *btn = [self cirlcleButtonAtIndex:index];
//            btn.backgroundColor = ACArticleNormalColor();
            UIButton *btnPlaceholder = [self cirlcleButtonAtIndex:index];
            btnPlaceholder.size = CGSizeMake(ACArticleCirlceInnerDiameter, ACArticleCirlceInnerDiameter);
            btnPlaceholder.layer.masksToBounds = YES;
            btnPlaceholder.layer.cornerRadius = ACArticleCirlceInnerDiameter / 2;
            btnPlaceholder.backgroundColor = UICOLOR_MAKE_RGBINT(0xe5e5e5);
            [self addSubview:btnPlaceholder];
            btnPlaceholder.center = btn.center;
            
            UILabel *lbl = [[UILabel alloc] initWithFrame:[self circleFrameAtIndex:index]];
            lbl.text = selections[index];
            lbl.textColor = UICOLOR_MAKE_RGBINT(0x333333);
            lbl.font = [UIFont systemFontOfSize:ACArticleFontSize(index)];
            titleSize = [ACArticleFontTitle(index) sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:ACArticleFontSize(index)]}];
            lbl.width = titleSize.width;
            lbl.center = btn.center;
            lbl.top = btn.bottom - 15 + step * index;
            NSTextAlignment textAlignment = NSTextAlignmentCenter;
            lbl.textAlignment = textAlignment;
            [marrCicles addObject:btn];
            [self addSubview:btn];
            [self addSubview:lbl];
        }
        arrCircles = [marrCicles copy];
        
        slCicles.path = bpHorizonLine.CGPath;
        glGradientCircles.mask = slCicles;
        ///添加选中的圆圈
        vSelected = [[UIImageView alloc] initWithFrame:CGRectMake([self circleCenterXAtIndex:selectedIndex] - ACArticleSelectedIndicatorWidth / 2, (ACArticleCirlceOutterDiameter - ACArticleSelectedIndicatorWidth) / 2, ACArticleSelectedIndicatorWidth, ACArticleSelectedIndicatorWidth)];
//        vSelected.layer.cornerRadius = ACArticleSelectedIndicatorWidth / 2;
//        vSelected.layer.masksToBounds = YES;
        vSelected.image = [UIImage imageNamed:@"article_font_picker_indicator"];
        
        [self addSubview:maskView];
        [maskView.layer addSublayer:glGradientCircles];
        [self addSubview:vSelected];
        [self updateMaskViewWithIndex:selectedIndex];
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        [self addGestureRecognizer:pan];
    }
    return self;
}

- (CAShapeLayer *)generateShapeLayer {
    CGFloat lineWidth = 5;
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.backgroundColor = [UIColor clearColor].CGColor;
    shapeLayer.frame = self.bounds;
    shapeLayer.lineWidth = lineWidth;
    return shapeLayer;
}

- (CAGradientLayer *)gradientLineLayer {
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.bounds;
    UIColor *fromColor = (id)UICOLOR_MAKE_RGBINT(0xfd8503).CGColor;
    UIColor *toColor = (id)UICOLOR_MAKE_RGBINT(0xe61728).CGColor;
    gradient.colors = @[fromColor, toColor];
    gradient.startPoint = CGPointMake(firstTitleCenterX / self.width, 0);
    gradient.endPoint   = CGPointMake(lastTitleCenterX / self.width, 0);
//    gradient.backgroundColor = [UIColor redColor].CGColor;
    return gradient;
}

///根据index获取cicle的frame
- (CGRect)circleFrameAtIndex:(NSInteger)index {
    return CGRectMake([self circleCenterXAtIndex:index] - ACArticleCirlceOutterDiameter / 2, 0, ACArticleCirlceOutterDiameter, ACArticleCirlceOutterDiameter);
}

- (CGFloat)circleCenterXAtIndex:(NSInteger)index {
    return firstTitleCenterX + sliceWidth * index;
}

- (CGPoint)circleCenterAtIndex:(NSInteger)index {
    return CGPointMake([self circleCenterXAtIndex:index], ACArticleCirlceOutterDiameter / 2);
}

///根据xaxis
- (NSInteger)indexAtXAxis:(CGFloat)xAxis {
    return (NSInteger)((xAxis - firstTitleCenterX + sliceWidth / 2) / sliceWidth);
}

///圆圈左侧最小点
- (CGFloat)circleMinLeft {
    return [self circleCenterXAtIndex:0];
}

///圆圈右侧最小点
- (CGFloat)cirlceMaxRight {
    return [self circleCenterXAtIndex:totalSelectionsCount - 1];
}

///根据index获取button
- (UIButton *)cirlcleButtonAtIndex:(NSInteger)index {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = ACArticleCicleButtonBaseTag + index;
    [btn addTarget:self action:@selector(didClickAction:) forControlEvents:UIControlEventTouchUpInside];
    btn.frame = [self circleFrameAtIndex:index];
    btn.layer.cornerRadius = ACArticleCirlceOutterDiameter / 2;
    btn.layer.masksToBounds = YES;
    return btn;
}

#pragma mark - Actions
///放大范围的点击事件
- (void)didClickAction:(UIButton *)btn {
    NSInteger currentSelectIndex = btn.tag - ACArticleCicleButtonBaseTag;
    if (currentSelectIndex == selectedIndex) {
        return;
    }
    ///如果字号和之前不同记录打点
//    [ACStatist statistClickAdjustFontInArticleDetailPage];
    [self handleFontTypeChangeWithTargetIndex:currentSelectIndex];
    vSelected.center = btn.center;
}

///处理选中targetIndex事件
- (void)handleFontTypeChangeWithTargetIndex:(NSInteger)targetIndex {
    if (fontChangedAction) {
        CGFloat currentTargetScale = ACArticleFontTargetFontTypeFromCurrentFontType(targetIndex, selectedIndex);
        fontChangedAction(currentTargetScale);
    }
    selectedIndex = targetIndex;
    [self updateMaskViewWithIndex:selectedIndex];
    ACArticleFontTypeUpdateInSetting(selectedIndex);
}

- (void)panAction:(UIPanGestureRecognizer *)pan {
    CGFloat currentX = [pan locationInView:self].x;
    NSLog(@"****************currentX        %f",currentX);
    currentX = MAX(currentX, [self circleMinLeft]);
    currentX = MIN(currentX, [self cirlceMaxRight]);
    NSLog(@"---------------currentX        %f",currentX);
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        case UIGestureRecognizerStateChanged:
        {
            vSelected.left = currentX - vSelected.width / 2;
            [self updateMaskViewFrame:currentX];
        }
            break;
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            ///手势结束
            ///1.更新UI
            ///2.更新选中字体
            NSInteger targetIndex = [self indexAtXAxis:currentX];
            ///如果字号和之前字号选择不同,那么记录打点
            if (targetIndex != selectedIndex) {
//                [ACStatist statistClickAdjustFontInArticleDetailPage];
            }
            if (fontChangedAction) {
                CGFloat currentTargetScale = ACArticleFontTargetFontTypeFromCurrentFontType(targetIndex, selectedIndex);
                fontChangedAction(currentTargetScale);
            }
            selectedIndex = targetIndex;
            ACArticleFontTypeUpdateInSetting(selectedIndex);
            [UIView animateWithDuration:.3 animations:^{
                vSelected.left = firstTitleCenterX + sliceWidth * selectedIndex - ACArticleSelectedIndicatorWidth / 2;
                [self updateMaskViewWithIndex:selectedIndex];
            } completion:^(BOOL finished) {
                
            }];
        }
            break;
        default:
            break;
    }
}

- (void)didChangeFontAction:(void(^)(CGFloat))action {
    fontChangedAction = action;
}

#pragma mark - Update MaskViewFrame
- (void)updateMaskViewFrame:(CGFloat)currentX {
    maskView.width = currentX;
}

- (void)updateMaskViewWithIndex:(NSInteger)index {
    maskView.width = sliceWidth * index + firstTitleCenterX;
}

@end
